package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.List;

<#if cfg.xls>
import org.springframework.http.HttpHeaders;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.MediaType;
import com.alibaba.excel.EasyExcel;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
</#if>

<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>

</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
<#if swagger2>
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
</#if>

/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if swagger2>
@Api(value = "${entity}", tags = {"${table.comment!}接口"})
</#if>
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass}<${table.mapperName}, ${entity}, String> {
<#else>
public class ${table.controllerName} {
</#if>

    @Autowired
    private ${table.serviceName} service;

<#if swagger2>
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", paramType = "query", value = "页面大小", dataTypeClass = Integer.class, required = false),
            @ApiImplicitParam(name = "current", paramType = "query", value = "页码，从1开始", dataTypeClass = Integer.class, required = false),
    })
    @ApiOperation(value = "分页条件查询", notes = "条件查询(分页类型数据只在分页时返回)", nickname = "${entity}_page")
</#if>
    @GetMapping("/page")
    public IPage<${entity}> page(Page<${entity}> page, ${entity} model) {
        return service.page(page, Wrappers.lambdaQuery(model));
    }

    @GetMapping
<#if swagger2>
    @ApiOperation(value = "条件查询", notes = "条件查询", nickname = "${entity}_getAll")
</#if>
    public List<${entity}> findAll(${entity} model) {
        return service.list(Wrappers.lambdaQuery(model));
    }

    @GetMapping("/{id}")
<#if swagger2>
    @ApiOperation(value = "查询", notes = "根据ID查询", httpMethod = "GET", nickname = "${entity}_getById")
</#if>
    public ${entity} getById(@PathVariable("id") String id) {
        return service.getById(id);
    }

    @PostMapping
<#if swagger2>
    @ApiOperation(value = "保存", notes = "保存", httpMethod = "POST", nickname = "${entity}_save")
</#if>
    public boolean save(@RequestBody ${entity} model) {
        return service.save(model);
    }

    @PostMapping("/batch/save")
<#if swagger2>
    @ApiOperation(value = "批量保存", notes = "批量保存", httpMethod = "POST", nickname = "${entity}_saveBatch")
</#if>
    public boolean saveBatch(@RequestBody List<${entity}> models) {
        return service.saveBatch(models);
    }

    @PutMapping
<#if swagger2>
    @ApiOperation(value = "更新", notes = "更新", httpMethod = "PUT", nickname = "${entity}_update")
</#if>
    public boolean update(@RequestBody ${entity} model) {
        return service.updateById(model);
    }

    @DeleteMapping("/{id}")
<#if swagger2>
    @ApiOperation(value = "删除", notes = "删除", httpMethod = "DELETE", nickname = "${entity}_del")
</#if>
    public boolean del(@PathVariable String id) {
        return service.removeById(id);
    }

    @PostMapping("/batch/delete")
<#if swagger2>
    @ApiOperation(value = "批量删除", notes = "批量删除", httpMethod = "DELETE", nickname = "${entity}_dels")
</#if>
    public boolean dels(@RequestBody Collection<String> ids) {
        return service.removeByIds(ids);
    }

<#if cfg.xls>
    @GetMapping("/xls/download")
    <#if swagger2>
    @ApiOperation(value = "xls下载", notes = "xls下载", httpMethod = "GET")
    </#if>
    public void excelDownload(HttpServletResponse response, ${entity} model) throws IOException {
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String fileName = URLEncoder.encode("${table.comment!}" + "_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")), StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<${entity}> ls = service.list(Wrappers.lambdaQuery(model));
        EasyExcel.write(response.getOutputStream(), ${entity}.class).sheet("${table.comment!}").doWrite(ls);
    }

    @PostMapping("/xls/import")
    @ApiOperation(value = "xls导入", notes = "xls导入", httpMethod = "POST")
    public String xlsImport(MultipartFile xlsFile) throws IOException {
        EasyExcel.read(xlsFile.getInputStream(), ${entity}.class, new AnalysisEventListener<${entity}>() {
            private List<${entity}> cachedDataList = new ArrayList<>();

            @Override
            public void invoke(${entity} data, AnalysisContext context) {
                cachedDataList.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                service.saveBatch(cachedDataList);
            }

        }).excelType(ExcelTypeEnum.XLSX).sheet().doRead();
        return "success";
    }
</#if>
}
</#if>
